from sqlalchemy import Boolean, Column, Integer, String, Float, Text, ForeignKey, Enum, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base_class import Base
import enum

class OrderStatus(enum.Enum):
    pending = "pending"           # 待付款
    paid = "paid"                 # 已付款
    shipping = "shipping"         # 配送中
    completed = "completed"       # 已完成
    cancelled = "cancelled"       # 已取消
    refunding = "refunding"       # 退款中
    refunded = "refunded"         # 已退款

class CartItem(Base):
    __tablename__ = "cart_items"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    product_id = Column(Integer, ForeignKey("products.id"))
    quantity = Column(Integer, default=1)
    selected = Column(Boolean, default=True)  # 是否选中

    # 关联
    user = relationship("User")
    product = relationship("Product")

class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    order_number = Column(String(50), unique=True, index=True)  # 订单编号
    total_amount = Column(Float, nullable=False)  # 订单总金额
    status = Column(Enum(OrderStatus), default=OrderStatus.pending)
    address_id = Column(Integer, ForeignKey("addresses.id"))  # 收货地址
    payment_method = Column(String(50))  # 支付方式
    payment_id = Column(String(100))  # 支付流水号
    shipping_method = Column(String(50))  # 配送方式
    shipping_fee = Column(Float, default=0.0)  # 运费
    tracking_number = Column(String(100))  # 物流单号
    remark = Column(Text)  # 订单备注

    # 关联
    user = relationship("User", back_populates="orders")
    items = relationship("OrderItem", back_populates="order")
    reviews = relationship("OrderReview", back_populates="order")

class OrderItem(Base):
    __tablename__ = "order_items"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    product_id = Column(Integer, ForeignKey("products.id"))
    quantity = Column(Integer, nullable=False)
    price = Column(Float, nullable=False)  # 下单时的价格
    total_price = Column(Float, nullable=False)  # 小计金额

    # 关联
    order = relationship("Order", back_populates="items")
    product = relationship("Product")

class OrderReview(Base):
    __tablename__ = "order_reviews"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    product_id = Column(Integer, ForeignKey("products.id"))
    user_id = Column(Integer, ForeignKey("users.id"))
    rating = Column(Integer)  # 评分(1-5)
    content = Column(Text)  # 评价内容
    images = Column(Text)  # 评价图片，JSON格式存储图片URL列表
    is_anonymous = Column(Boolean, default=False)  # 是否匿名评价

    # 关联
    order = relationship("Order", back_populates="reviews")
    product = relationship("Product")
    user = relationship("User")